package com.zcs.android.app.jetpack.ui.main

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import com.zcs.android.app.jetpack.R
import com.zcs.android.app.jetpack.ui.main.vm.MainViewModel
import kotlinx.android.synthetic.main.main_fragment.*


class MainFragment : Fragment() {

    companion object {
        fun newInstance() = MainFragment()
    }

    private lateinit var viewModel: MainViewModel
    private var mLiveData: MutableLiveData<String>? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return inflater.inflate(R.layout.main_fragment, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        // TODO: Use the ViewModel
        message.text = viewModel.getMsg()

        btnUpdate.setOnClickListener {
            mLiveData?.value = "北京时间：${System.currentTimeMillis()}"
        }
        mLiveData = viewModel.getLiveData()
        mLiveData?.value = "onActivityCreated";

        mLiveData?.observe(this, {
            Log.d("observe", "observe called with $it")
            // 更新UI
            message.text = it
        })
    }

    override fun onResume() {
        super.onResume()
        mLiveData?.value = "onResume"
    }

    override fun onStop() {
        super.onStop()
        mLiveData?.value = "onStop"
    }

    override fun onDestroy() {
        super.onDestroy()
        mLiveData?.value = "onDestroy"
    }
}
